//
//  EmoticonVC.swift
//  测试2-表情键盘
//
//  Created by shmily on 15/8/6.
//  Copyright © 2015年 shmilyAshen. All rights reserved.
//

import UIKit

/// 显示表情键盘的控制器
class EmoticonVC: UIViewController {
    
    /// 显示内容的文本框
    var textView: UITextView?
    
    /// 数据
    private lazy var packages: [EmoticonPackage] = EmoticonPackage.packages
    
    
    /// 按钮点击事件
    func toolbarClick(sender: UIBarButtonItem) {
        //滚动到对应的分组
        let indexPath = NSIndexPath(forItem: 0, inSection: sender.tag)
        collectView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        
    }
        
    
    private func prepareUI() {
        view.addSubview(toolbar)
        view.addSubview(collectView)
        
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        collectView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv":collectView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb":toolbar]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv":collectView,"tb":toolbar]))
    }
    
    private func prepareCollection() {
        collectView.backgroundColor = UIColor.whiteColor()
        collectView.registerClass(collectCell.self, forCellWithReuseIdentifier: "collectCell")
        collectView.dataSource = self
        collectView.delegate = self
    }
    
    /// 构造函数
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
        prepareUI()
        prepareCollection()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 懒加载
    private lazy var collectView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout:  collectionLayout())
    
    private lazy var toolbar: UIToolbar = {
        let bar = UIToolbar()
        var items = [UIBarButtonItem]()
        
        let names = ["最近","默认","emoji","浪小花"]
        var index = 0
        for name in names {
            let bar = UIBarButtonItem(title: name, style: UIBarButtonItemStyle.Plain, target: self, action: "toolbarClick:")
            bar.tag = index++
           items.append(bar)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        bar.items = items
        
        return bar
    }()
}


// MARK: - 数据源方法
extension EmoticonVC: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectView.dequeueReusableCellWithReuseIdentifier("collectCell", forIndexPath: indexPath) as! collectCell
        //TODO:处理 cell
        cell.emoticon = packages[indexPath.section].emoticons?[indexPath.row]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    
    /// 单击按钮事件
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //删除图标
        if (indexPath.row + 1) % 21 == 0 {
            textView?.deleteBackward()
            return
        }
        //添加图标
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        textView?.insertEmoticon(emoticon)
        //手动调用代理方法
        textView!.delegate!.textViewDidChange!(textView!)
        
        if indexPath.section != 0 {
            sortEmoticon(emoticon) // 排序
            collectionView.reloadSections(NSIndexSet(index: 0))
        }
    }
    
    /// 对最近的表情进行排序操作
    private func sortEmoticon(emoticon: Emoticon) {
        //对第一组进行修改,判断是否已经存在,不存在的话,添加一个(必须删除最后一个,永远保持21个),重新排序,赋值后返回
        emoticon.times++ //单击一次,计数器+1
        var emos = packages[0].emoticons!
        emos.removeLast() //删除删除按钮(不进行排序)
        
        let contains = emos.contains(emoticon)
        if !contains { //如果不包含就追加,并且删除最后一个
             emos.append(emoticon)
        }
        
        var sortedEmos = emos.sort { return $0.times > $1.times}
        
        if !contains { //排序好之后再删除(可能最后添加的是最后一个)
             sortedEmos.removeLast()
        }
        
        sortedEmos.append(Emoticon(delete: true)) //添加删除按钮
        
        packages[0].emoticons = sortedEmos
    }
}

/// coleciton的 cell
class collectCell: UICollectionViewCell {
    
    /// 内容
    var emoticon: Emoticon?{
        didSet{
            currentBtn.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            currentBtn.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            currentBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
            //如果是删除按钮
            if emoticon?.deleteBtn == true {
                 currentBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            } //空白按钮自动实现,不需要其他操作
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(currentBtn)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载
    private lazy var currentBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.whiteColor()
        btn.frame = CGRectInset(self.contentView.bounds, 3, 3)
        btn.userInteractionEnabled = false
        return btn
    }()
}

/// collectionView 的流式布局
class collectionLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        let width = UIScreen.mainScreen().bounds.width / 7
        itemSize = CGSize(width: width, height: width)

        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
    }
}
